package com.xu.cloud.common.desensitization;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 脱敏处理器, 反射实现
 *
 * @author xuguan
 * @since 2025/3/5
 */
public class DesensitizationHandler {

    private final IDeSensitizationRuleFactory ruleFactory;

    public DesensitizationHandler(IDeSensitizationRuleFactory ruleFactory) {
        this.ruleFactory = ruleFactory;
    }

    public void desensitization(@Nullable Object obj) {
        if (Objects.isNull(obj)) {
            return;
        }
        final Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!AnnotatedElementUtils.hasAnnotation(field, Desensitization.class)) {
                continue;
            }
            if (!String.class.isAssignableFrom(field.getType())) {
                continue;
            }
            final AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(field, Desensitization.class);
            Assert.notNull(attributes, "annotation attributes must not be null");
            SensitizationEnum sensitizationEnum = (SensitizationEnum) attributes.get("value");
            ReflectionUtils.makeAccessible(field);
            final String source = (String) ReflectionUtils.getField(field, obj);
            final IDesensitizationRule rule = ruleFactory.getRule(sensitizationEnum);
            final String target = rule.desensitization(source);
            ReflectionUtils.setField(field, obj, target);
        }
    }
}
